package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.CalculateFreightBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.db.CityHistoryBean;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.CityUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.CommonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LocationUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.NumberUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SelectUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Descriptions：下单
 * <p>
 * Author：ChenME
 * Date：2017/1/6
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_place_order_v2)
public class PlaceOrderActivityV2 extends AppBaseActivity {

    //    @Bean(ConstantUtils.class)
//    ConstantUtils cUtils;
    @Bean(CommonUtils.class)
    CommonUtils commUtils;

    @ViewById(R.id.tv_fromInfo)
    TextView tv_fromInfo;
    @ViewById(R.id.tv_fromPersonInfo)
    TextView tv_fromPersonInfo;

    @ViewById(R.id.tv_toInfo)
    TextView tv_toInfo;
    @ViewById(R.id.tv_toPersonInfo)
    TextView tv_toPersonInfo;

    @ViewById(R.id.et_goodsName)
    EditText et_goodsName;
    @ViewById(R.id.et_weight)
    EditText et_weight;
    @ViewById(R.id.et_volume)
    EditText et_volume;
    @ViewById(R.id.et_goodsCnt)
    EditText et_goodsCnt;

    @ViewById(R.id.et_SalesmanName)
    EditText et_SalesmanName; //业务员姓名

    @ViewById(R.id.rg_userType)
    RadioGroup rg_userType;
    @ViewById(R.id.rb_typeCommon)
    RadioButton rb_typeCommon;
    @ViewById(R.id.rb_typeA)
    RadioButton rb_typeA;
    @ViewById(R.id.rb_typeB)
    RadioButton rb_typeB;

    @ViewById(R.id.switch_getGoodsWay)
    Switch switch_getGoodsWay;
    @ViewById(R.id.tv_getGoodsFee)
    TextView tv_getGoodsFee;

    @ViewById(R.id.switch_sendGoodsWay)
    Switch switch_sendGoodsWay;
    @ViewById(R.id.tv_sendGoodsFee)
    TextView tv_sendGoodsFee;

    @ViewById(R.id.tv_payWay)
    TextView tv_payWay;

    @ViewById(R.id.et_remarks)
    EditText et_remarks;

    @Extra("fromWhichPage")
    int fromWhichPage;//从哪个界面跳转，是否获取详情
    @Extra("orderId")
    String orderId;

    private final int Request_FastOrder = 0x1121;//快速下单
    private final int Request_FromInfo = 0x1122;//填写发件信息
    private final int Request_ToInfo = 0x1123;//填写收件信息

    private final String UserType_Comm = "0";
    private final String UserType_A = "1";
    private final String UserType_B = "2";

    private String orderCode = "";

    private String resultFromPerson = "";
    private String resultFromPhone = "";
    private String resultFromAddress = "";
    private String resultFromPCA = "";
    private CityHistoryBean resultFromCityInstance;
    private String resultFromProvinceCode = "";
    private String resultFromCityCode = "";
    private String resultFromAreaCode = "";

    private String startGpsX = "0";//
    private String startGpsY = "0";//
    private String endGpsX = "0";//
    private String endGpsY = "0";//

    private String resultToPerson = "";
    private String resultToPhone = "";
    private String resultToAddress = "";
    private String resultToPCA = "";
    private CityHistoryBean resultToCityInstance;
    private String resultToProvinceCode = "";
    private String resultToCityCode = "";
    private String resultToAreaCode = "";

    private String resultGoodsName;
    private String resultWeight;
    private String resultVolume;
    private String resultGoodsCnt;
    private String resultSalesmanName;
    private String resultUserType = UserType_Comm;

    final int PickFeeMin = 4000;
    final int SendFeeMin = 5000;
    private int resultPickFee = PickFeeMin;
    private int resultSendFee = SendFeeMin;

    private String actualMoney;//已经支付的金额

    private String resultPayWay;

    private String resultRemark;

    private int pickFeeIndex = 0;//-1：不可点击
    //    private String[] pickFeeArr, sendFeeArr;
    private int sendFeeIndex = 0;//-1：不可点击


    private LocalBroadcastManager lbm;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastChannels.Channel_CreateOrderSuccessFully)) {
                finish();
                animUtils.leftOutAnimation(PlaceOrderActivityV2.this);
            }
        }
    };


    @AfterViews
    void onPageStart() {
        LocationUtil.getAndSaveLocation2SharePreference(this);
        registerMyReceiver();

        initFeeView();

        if (Flag.ToPlaceOrder_FromOrderDetail == fromWhichPage) {//修改订单
            setDefaultTitle(this, R.string.string_alter_order);
            getOrderDetail();
        } else {
            setTitle(this, R.string.string_placeOrderV2_title, R.drawable.comm_press_return_selector,
                    true, new OnNavigationBtnClickListener() {
                        @Override
                        public void navigationClick() {
                            onBackPressed();
                        }

                        @Override
                        public void menuItemClick(MenuItem item) {
                            switch (item.getItemId()) {
                                case R.id.menuItem1:
                                    FastOrder_CommSendOrPickUpInfo_Activity_.intent(PlaceOrderActivityV2.this)
                                            .whichPage(FastOrder_CommSendOrPickUpInfo_Activity.Page_FastOrder)
                                            .startForResult(Request_FastOrder);
                                    animUtils.leftInAnimation(PlaceOrderActivityV2.this);
                                    break;
                            }
                        }
                    });
        }

        rg_userType.setOnCheckedChangeListener((radioGroup, checkedId) -> {
            if (checkedId == rb_typeCommon.getId()) {
                resultUserType = UserType_Comm;
            } else if (checkedId == rb_typeA.getId()) {
                resultUserType = UserType_A;
            } else {
                resultUserType = UserType_B;
            }
        });
    }

    /**
     * 初始化取送货费用的View
     */
    private void initFeeView() {
//        pickFeeArr = cUtils.getPickGoodsFee();
//        sendFeeArr = cUtils.getSendGoodsFee();

        updatePickGoodsFeeView();
        updateSendGoodsFeeView();

        switch_getGoodsWay.setOnCheckedChangeListener((buttonView, isChecked) -> {
            pickFeeIndex = isChecked ? 0 : -1;
            updatePickGoodsFeeView();
        });
        switch_sendGoodsWay.setOnCheckedChangeListener((buttonView, isChecked) -> {
            sendFeeIndex = isChecked ? 0 : -1;
            updateSendGoodsFeeView();
        });
    }

    /**
     * 更新送货费View
     */
    private void updateSendGoodsFeeView() {
        if (sendFeeIndex < 0) {
            tv_sendGoodsFee.setText(Html.fromHtml(String.format(getString(R.string.string_placeOrderV2_sendGoodsWayFee), "0")));
            tv_sendGoodsFee.setEnabled(false);
            return;
        }
        tv_sendGoodsFee.setText(Html.fromHtml(String.format(getString(R.string.string_placeOrderV2_sendGoodsWayFee),
                resultSendFee / 100 + "")));
        tv_sendGoodsFee.setEnabled(true);
    }

    /**
     * 更新收货费View
     */
    private void updatePickGoodsFeeView() {
        if (pickFeeIndex < 0) {
            tv_getGoodsFee.setText(Html.fromHtml(String.format(getString(R.string.string_placeOrderV2_getGoodsWayFee), "0")));
            tv_getGoodsFee.setEnabled(false);
            return;
        }
        tv_getGoodsFee.setText(Html.fromHtml(String.format(getString(R.string.string_placeOrderV2_getGoodsWayFee),
                resultPickFee / 100 + "")));
        tv_getGoodsFee.setEnabled(true);
    }

    /**
     * 注册广播
     */
    private void registerMyReceiver() {
        lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastChannels.Channel_CreateOrderSuccessFully);
        lbm.registerReceiver(receiver, filter);
    }

    /**
     * 发件信息返回结果
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_FromInfo)
    void onFromResult(int resultCode, Intent data) {
        if (EditSendOrPickUpInfoActivity.Result_CompleteInfo == resultCode) {
            resultFromCityInstance = data.getParcelableExtra("resultCityBean");

//            getGaoCode(resultFromCityInstance.getCity(), resultFromCityInstance.getArea(), "s");

            resultFromProvinceCode = resultFromCityInstance.getProvinceCode();
            resultFromCityCode = resultFromCityInstance.getCityCode();
            resultFromAreaCode = resultFromCityInstance.getAreaCode();

            resultFromPerson = data.getStringExtra("resultPerson");
            resultFromPhone = data.getStringExtra("resultPhone");
            resultFromAddress = data.getStringExtra("resultAddress");
            startGpsX = data.getStringExtra("resultGpsX");
            startGpsY = data.getStringExtra("resultGpsY");
            resultFromPCA = resultFromCityInstance.getProvince() + resultFromCityInstance.getCity() + resultFromCityInstance.getArea();

            bindFromInfoData2View();
        }
    }

    /**
     * 将发货信息显示出来，
     */
    private void bindFromInfoData2View() {
        tv_fromInfo.setText(resultFromPCA + resultFromAddress);
        tv_fromPersonInfo.setVisibility(View.VISIBLE);
        tv_fromPersonInfo.setText(resultFromPerson + "  " + resultFromPhone);
    }


    /**
     * 显示取送货费用的对话框
     *
     * @param isPick 是否是取货
     */
    private void showFeeDialog(boolean isPick) {

        Dialog view = new Dialog(this, R.style.DialogFullWindowStyle);// 创建自定义样式dialog

        view.setCancelable(false);// 不可以用“返回键”取消
        view.setContentView(R.layout.dialog_show_pick_or_send_fee);// 设置布局

        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        ImageButton iBtn_close = (ImageButton) view.findViewById(R.id.iBtn_close);
        EditText et_money = (EditText) view.findViewById(R.id.et_money);
//        RadioGroup rg_feeList = (RadioGroup) view.findViewById(R.id.rg_feeList);

        String title = isPick ? getString(R.string.string_placeOrderV2_getGoodsTitle) :
                getString(R.string.string_placeOrderV2_sendGoodsTitle);
        tv_title.setText(title);

        iBtn_close.setOnClickListener(v -> view.dismiss());

        view.findViewById(R.id.btn_confirmMoney).setOnClickListener(v -> {
            String money = et_money.getText().toString().trim();
            if (StringUtils.isEmpty(money)) {
                App.toast("请输入正确的金额！");
            } else {
                try {
                    int temp = Integer.valueOf(money) * 100;
                    if (isPick) {
                        if (temp < PickFeeMin) {
                            App.toast("取货费最小金额为" + PickFeeMin / 100 + "元");
                        } else {
                            resultPickFee = temp;
                            updatePickGoodsFeeView();
                            view.dismiss();
                        }
                    } else {
                        if (temp < SendFeeMin) {
                            App.toast("送货费最小金额为" + SendFeeMin / 100 + "元");
                        } else {
                            resultSendFee = temp;
                            updateSendGoodsFeeView();
                            view.dismiss();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

//        String[] items = isPick ? pickFeeArr : sendFeeArr;
//        for (int i = 0; i < items.length; i++) {
//            RadioButton rBtn = new RadioButton(this);
//            rBtn.setText("￥" + items[i]);
//            rBtn.setTextSize(20);
//            rBtn.setId(i);
//            rg_feeList.addView(rBtn);
//        }
//
//        ((RadioButton) rg_feeList.getChildAt(isPick ? pickFeeIndex : sendFeeIndex)).setChecked(true);
//        rg_feeList.setOnCheckedChangeListener((group, checkedId) -> {
//
//            if (isPick) {
//                pickFeeIndex = checkedId;
//                updatePickGoodsFeeView();
//            } else {
//                sendFeeIndex = checkedId;
//                updateSendGoodsFeeView();
//            }
//            view.dismiss();
//        });

        view.show();
        et_money.requestFocus();
    }


    @Click(R.id.tv_getGoodsFee)
    void onGetGoodsFeeClick() {
        showFeeDialog(true);
    }

    @Click(R.id.tv_sendGoodsFee)
    void onSendGoodsFeeClick() {
        showFeeDialog(false);
    }

    /**
     * 收件信息返回结果
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_ToInfo)
    void onToResult(int resultCode, Intent data) {
        if (EditSendOrPickUpInfoActivity.Result_CompleteInfo == resultCode) {
            resultToCityInstance = data.getParcelableExtra("resultCityBean");

//            getGaoCode(resultToCityInstance.getCity(), resultToCityInstance.getArea(), "r");

            resultToProvinceCode = resultToCityInstance.getProvinceCode();
            resultToCityCode = resultToCityInstance.getCityCode();
            resultToAreaCode = resultToCityInstance.getAreaCode();

            resultToPerson = data.getStringExtra("resultPerson");
            resultToPhone = data.getStringExtra("resultPhone");
            resultToAddress = data.getStringExtra("resultAddress");
            endGpsX = data.getStringExtra("resultGpsX");
            endGpsY = data.getStringExtra("resultGpsY");

            resultToPCA = resultToCityInstance.getProvince() + resultToCityInstance.getCity() + resultToCityInstance.getArea();
            bindToInfoData2View();
        }
    }

    /**
     * 将收货信息显示出来，
     */
    private void bindToInfoData2View() {
        tv_toInfo.setText(resultToPCA + resultToAddress);
        tv_toPersonInfo.setVisibility(View.VISIBLE);
        tv_toPersonInfo.setText(resultToPerson + "  " + resultToPhone);
    }

    /**
     * 快速下单返回结果
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Request_FastOrder)
    void onFastOrderResult(int resultCode, Intent data) {
        if (FastOrder_CommSendOrPickUpInfo_Activity.Result_CompleteOrderChose == resultCode) {

            analysisDataFromOrderBean(data.getParcelableExtra("orderBean"));

            bindAllData2View();
        }
    }

//    /**
//     * 根据城市名称获取经纬度
//     *
//     * @param city
//     * @param area
//     */
//    private void getGaoCode(String city, String area, String type) {
//        geoCode = LocationUtil.calculateFreight(this, city, area, type);
//    }

    /**
     * 发货信息
     */
    @Click(R.id.ll_fromInfo)
    void onFromInfoClick() {
        EditSendOrPickUpInfoActivity_.intent(this)
                .whichPage(EditSendOrPickUpInfoActivity.Page_FromInfo)
                .resultCityBean(resultFromCityInstance)
                .resultPerson(resultFromPerson)
                .resultPhone(resultFromPhone)
                .resultAddress(resultFromAddress)
                .startForResult(Request_FromInfo);
        animUtils.leftInAnimation(this);
    }

    /**
     * 收货信息
     */
    @Click(R.id.ll_toInfo)
    void onToInfoClick() {
        EditSendOrPickUpInfoActivity_.intent(this)
                .whichPage(EditSendOrPickUpInfoActivity.Page_ToInfo)
                .resultCityBean(resultToCityInstance)
                .resultPerson(resultToPerson)
                .resultPhone(resultToPhone)
                .resultAddress(resultToAddress)
                .startForResult(Request_ToInfo);
        animUtils.leftInAnimation(this);
    }

    /**
     * 支付方式
     * 1：在线支付
     * 2：现金
     * 3：到付
     * 4：回单付
     * 5：预付
     * 6：月付
     */
    @Click(R.id.ll_payWay)
    void onPayWayClick() {
        String[] items = {getString(R.string.string_placeOrderV2_payWayOnline)
                , getString(R.string.string_placeOrderV2_payWayCash)
                , getString(R.string.string_placeOrderV2_payWayArrive)
                , getString(R.string.string_placeOrderV2_payWayHalfPay)
                , getString(R.string.string_placeOrderV2_payWayAdvance)
                , getString(R.string.string_placeOrderV2_payWayMonth)
        };
        //创建对话框
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.string_place_order_pay_way_hint))//设置对话框标题
                .setItems(items, (dialog, which) -> {
                    if (which == 0) {
                        resultPayWay = "1";
                        tv_payWay.setText(items[0]);
                    } else if (which == 1) {
                        resultPayWay = "2";
                        tv_payWay.setText(items[1]);
                    } else if (which == 2) {
                        resultPayWay = "3";
                        tv_payWay.setText(items[2]);
                    } else if (which == 3) {

                        resultPayWay = "4";
                        tv_payWay.setText(items[3]);
                    } else if (which == 4) {
                        resultPayWay = "5";
                        tv_payWay.setText(items[4]);
                    } else if (which == 5) {
                        resultPayWay = "6";
                        tv_payWay.setText(items[5]);
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())//设置对话框[否定]按钮
                .show();
    }

    /**
     * 计算体积
     */
    @Click(R.id.tv_calculateVolumeBtn)
    void calculateVolumeClick() {

        Dialog view = new Dialog(this, R.style.DialogFullWindowStyle);// 创建自定义样式dialog

        view.setCancelable(false);// 不可以用“返回键”取消
        view.setContentView(R.layout.dialog_calculate_volume);// 设置布局

        EditText et_length = (EditText) view.findViewById(R.id.et_length);
        EditText et_width = (EditText) view.findViewById(R.id.et_width);
        EditText et_height = (EditText) view.findViewById(R.id.et_height);


        view.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            String lengthTemp = et_length.getText().toString().trim();
            String widthTemp = et_width.getText().toString().trim();
            String heightTemp = et_height.getText().toString().trim();
            if (StringUtils.isEmpty(lengthTemp) ||
                    StringUtils.isEmpty(widthTemp) ||
                    StringUtils.isEmpty(heightTemp)) {
                App.toast("请填入完整的货物体积信息！");
                return;
            }
            double result = Double.valueOf(lengthTemp) *
                    Double.valueOf(widthTemp) *
                    Double.valueOf(heightTemp) / 1000000;
            et_volume.setText(NumberUtils.formatDouble(result, "0.00") + "");
            view.dismiss();
        });

        view.findViewById(R.id.iBtn_close).setOnClickListener(v -> view.dismiss());
        view.show();
    }

    /**
     * 提交订单
     */
    @Click(R.id.btn_commitBtn)
    void onCommitClick() {
        if (null == resultFromCityInstance) {
            App.toast("请填写发货信息");
            return;
        }
        if (null == resultToCityInstance) {
            App.toast("请填写收货信息");
            return;
        }
        resultGoodsName = et_goodsName.getText().toString().trim();
        if (StringUtils.isEmpty(resultGoodsName)) {
            App.toast("请填写货物名称");
            return;
        }
        resultWeight = et_weight.getText().toString().trim();
        if (StringUtils.isEmpty(resultWeight)) {
            App.toast("请输入货物重量");
            return;
        }
        resultVolume = et_volume.getText().toString().trim();
        if (StringUtils.isEmpty(resultVolume)) {
            App.toast("请输入货物体积");
            return;
        }
        resultGoodsCnt = et_goodsCnt.getText().toString().trim();
        if (StringUtils.isEmpty(resultGoodsCnt)) {
            App.toast("请输入货物总件数");
            return;
        }
        String resultPayWayTem = tv_payWay.getText().toString().trim();
        if (StringUtils.isEmpty(resultPayWayTem)) {
            App.toast("请选择支付方式");
            return;
        }

        resultSalesmanName = et_SalesmanName.getText().toString().trim();

        resultPickFee = pickFeeIndex == -1 ? 0 : resultPickFee;
//        resultGetGoodsWay = switch_getGoodsWay.isChecked() ? "0" : "1";
        resultSendFee = sendFeeIndex == -1 ? 0 : resultSendFee;

        resultRemark = et_remarks.getText().toString().trim();

        calculateFreight();
//        calculateDistanceBetweenStartAndEnd();
    }

    /**
     * 计算始发地与目的地之间的距离
     */
//    private void calculateDistanceBetweenStartAndEnd() {
//        String latSTemp = SharePreferenceUtil.getLocationS(this).getGps_y();
//        String latRTemp = SharePreferenceUtil.getLocationR(this).getGps_y();
//        String lonSTemp = SharePreferenceUtil.getLocationS(this).getGps_x();
//        String lonRTemp = SharePreferenceUtil.getLocationR(this).getGps_x();
//        if (StringUtils.isEmpty(latSTemp) &&
//                StringUtils.isEmpty(latRTemp) &&
//                StringUtils.isEmpty(lonSTemp) &&
//                StringUtils.isEmpty(lonRTemp)) {
//            return;
//        }
//        double latS = Double.valueOf(latSTemp);
//        double latR = Double.valueOf(latRTemp);
//        double lonS = Double.valueOf(lonSTemp);
//        double lonR = Double.valueOf(lonRTemp);


//        LatLng sLatLng = new LatLng(latS, lonS);
//        LatLng rLayLng = new LatLng(latR, lonR);

//        String distance = String.valueOf(Math.ceil(DistanceUtil.getDistance(sLatLng, rLayLng)));

//        calculateFreight();
//    }

    /**
     * 计算运费
     */
    private void calculateFreight() {

        CalculateFreightBean calculate = new CalculateFreightBean(resultWeight, resultVolume, resultUserType,
                resultFromProvinceCode, resultFromCityCode, resultFromAreaCode, resultFromAddress,
                resultToProvinceCode, resultToCityCode, resultToAreaCode, resultToAddress,
                resultPickFee + "", resultSendFee + "");
        String jsonCalculate = JsonUtils.createJsonString(calculate);
        try {
            String aesCalculate = JsonUtils.aes(jsonCalculate);
            callNet(this, InterfaceNet.Net_CalculateFreightNew, aesCalculate, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    CalculateFreightBean calculate = (CalculateFreightBean) JsonUtils.parseJsonString(content, CalculateFreightBean.class);
                    String freight = calculate.getFreight();
                    if (!StringUtils.isEmpty(freight)) {

                        SharePreferenceUtil.saveOrderPlace(PlaceOrderActivityV2.this,
                                resultFromPerson, resultFromPhone, resultToPerson, resultToPhone,
                                resultFromProvinceCode, resultFromCityCode, resultFromAreaCode, resultFromAddress,
                                resultToProvinceCode, resultToCityCode, resultToAreaCode, resultToAddress,
                                resultGoodsName, resultWeight, resultVolume, freight, resultRemark,
                                resultPayWay, resultFromPCA, resultToPCA, resultUserType, resultGoodsCnt);

                        OrderBean orderBean = fillOrderBean();
                        orderBean.setSalesman(resultSalesmanName);
                        orderBean.setDealPrice(freight);
                        List<String[]> priceList = new ArrayList<>();
                        priceList.addAll(calculate.getDiscountInfo());
                        String basePrice = calculate.getBaseFreight();
                        OrderPlaceSureActivity_.intent(PlaceOrderActivityV2.this)
                                .basePrice(basePrice)
                                .priceInfoList(priceList)
                                .fromWhichPage(fromWhichPage)
                                .selfPickUpFreight(calculate.getSelfPickUpFreight())
                                .selfSendFreight(calculate.getSelfSendFreight())
                                .orderBean(orderBean).start();
                        animUtils.leftInAnimation(PlaceOrderActivityV2.this);
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取订单详情
     */
    private void getOrderDetail() {
        OrderBean orderBeanDetail = new OrderBean(orderId);
        String jsonOrderDetail = JsonUtils.createJsonString(orderBeanDetail);
        try {
            String aesOrderDetail = JsonUtils.aes(jsonOrderDetail);
            callNet(PlaceOrderActivityV2.this, InterfaceNet.Net_GetOrderDetailByOrderID, aesOrderDetail, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {
                        OrderBean orderBean = (OrderBean) JsonUtils.parseJsonString(content, OrderBean.class);

                        analysisDataFromOrderBean(orderBean);

                        bindAllData2View();
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据从OrderBean中解析出来
     *
     * @param orderBean
     */
    private void analysisDataFromOrderBean(OrderBean orderBean) {

        CityUtil cityUtil = new CityUtil(this);

        resultFromProvinceCode = orderBean.getStartProvince();
        resultFromCityCode = orderBean.getStartCity();
        resultFromAreaCode = orderBean.getStartArea();
        String fromProvince = cityUtil.findProvinceName(resultFromProvinceCode);
        String fromCity = cityUtil.findCityName(resultFromCityCode);
        String fromArea = cityUtil.findAreaName(resultFromAreaCode);
//        getGaoCode(fromCity, fromArea, "s");
        resultFromCityInstance = new CityHistoryBean(resultFromAreaCode, resultFromCityCode,
                resultFromProvinceCode, fromArea, fromCity, fromProvince);

        resultFromPCA = fromProvince + fromCity + fromArea;
        resultFromAddress = orderBean.getStartAddress();

        resultFromPerson = orderBean.getConsignorName();
        resultFromPhone = orderBean.getConsignorMobile();

        resultToProvinceCode = orderBean.getEndProvince();
        resultToCityCode = orderBean.getEndCity();
        resultToAreaCode = orderBean.getEndArea();
        String toProvince = cityUtil.findProvinceName(resultToProvinceCode);
        String toCity = cityUtil.findCityName(resultToCityCode);
        String toArea = cityUtil.findAreaName(resultToAreaCode);
//        getGaoCode(toCity, toArea, "r");
        resultToCityInstance = new CityHistoryBean(resultToAreaCode, resultToCityCode,
                resultToProvinceCode, toArea, toCity, toProvince);

        resultToPCA = toProvince + toCity + toArea;

        resultToAddress = orderBean.getEndAddress();

        resultToPerson = orderBean.getConsigneeName();
        resultToPhone = orderBean.getConsigneeMobile();

        resultGoodsName = orderBean.getGoodsName();
        resultWeight = orderBean.getGoodsWeight();
        resultVolume = orderBean.getGoodsVolume();
        resultGoodsCnt = orderBean.getGoodsCount();
        resultUserType = orderBean.getCalculateType();

        String tempPickFee = orderBean.getSelfSendFreight();
        String tempSendFee = orderBean.getSelfPickUpFreight();

        try {
            if (!StringUtils.isEmpty(tempPickFee)) {
                resultPickFee = Integer.valueOf(tempPickFee);
            }
            if (!StringUtils.isEmpty(tempSendFee)) {
                resultSendFee = Integer.valueOf(tempSendFee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultPayWay = orderBean.getPayType();
        orderCode = orderBean.getOrderCode();

        actualMoney = orderBean.getActualMoney();

        resultRemark = orderBean.getRemarks();

        resultSalesmanName = orderBean.getSalesman();

        startGpsX = orderBean.getStartGpsX();
        startGpsY = orderBean.getStartGpsY();
        endGpsX = orderBean.getEndGpsX();
        endGpsY = orderBean.getEndGpsY();
    }

    /**
     * 将所有的数据都绑定到控件上
     */
    private void bindAllData2View() {
        bindFromInfoData2View();
        bindToInfoData2View();
        et_goodsName.setText(resultGoodsName);
        et_weight.setText(StringUtils.dropNeedlessZeroOfNum(resultWeight));
        et_volume.setText(StringUtils.dropNeedlessZeroOfNum(resultVolume));
        et_SalesmanName.setText(resultSalesmanName);
        et_goodsCnt.setText(resultGoodsCnt);

        if (UserType_Comm.equals(resultUserType)) {
            rb_typeCommon.setChecked(true);
        } else if (UserType_A.equals(resultUserType)) {
            rb_typeA.setChecked(true);
        } else if (UserType_B.equals(resultUserType)) {
            rb_typeB.setChecked(true);
        }

        try {
            int tempPickFee = Integer.valueOf(resultPickFee);
//            String tPickFeeStr = (tempPickFee / 100) + "";
            if (tempPickFee <= 0) {
                switch_getGoodsWay.setChecked(false);
                tv_getGoodsFee.setEnabled(false);
                pickFeeIndex = -1;
            } else {
                switch_getGoodsWay.setChecked(true);
                tv_getGoodsFee.setEnabled(true);
//                for (int i = 0; i < pickFeeArr.length; i++) {
//                    if (pickFeeArr[i].equals(tPickFeeStr)) {
//                        pickFeeIndex = i;
//                        break;
//                    }
//                }
            }
            updatePickGoodsFeeView();

            int tempSendFee = Integer.valueOf(resultSendFee);
//            String tSendFeeStr = (tempSendFee / 100) + "";
            if (tempSendFee <= 0) {
                switch_sendGoodsWay.setChecked(false);
                tv_sendGoodsFee.setEnabled(false);
                sendFeeIndex = -1;
            } else {
                switch_sendGoodsWay.setChecked(true);
                tv_sendGoodsFee.setEnabled(true);
//                for (int i = 0; i < sendFeeArr.length; i++) {
//                    if (sendFeeArr[i].equals(tSendFeeStr)) {
//                        sendFeeIndex = i;
//                        break;
//                    }
//                }
            }
            updateSendGoodsFeeView();
        } catch (Exception e) {
            e.printStackTrace();
        }

        tv_payWay.setText(SelectUtil.initPayWay().get(resultPayWay));
        et_remarks.setText(resultRemark);
    }


    /**
     * 将数据填充到OrderBean中
     */
    private OrderBean fillOrderBean() {
        OrderBean orderBean = new OrderBean();
        orderBean.setConsignorName(resultFromPerson);
        orderBean.setConsignorMobile(resultFromPhone);
        orderBean.setConsigneeName(resultToPerson);
        orderBean.setConsigneeMobile(resultToPhone);
        orderBean.setStartProvince(resultFromProvinceCode);
        orderBean.setStartCity(resultFromCityCode);
        orderBean.setStartArea(resultFromAreaCode);
        orderBean.setStartAddress(resultFromAddress);
        orderBean.setEndProvince(resultToProvinceCode);
        orderBean.setEndCity(resultToCityCode);
        orderBean.setEndArea(resultToAreaCode);
        orderBean.setEndAddress(resultToAddress);
        orderBean.setGoodsName(resultGoodsName);
        orderBean.setGoodsWeight(resultWeight);
        orderBean.setGoodsVolume(resultVolume);
        orderBean.setRemarks(resultRemark);
        orderBean.setPayType(resultPayWay);
        orderBean.setStatus(getString(R.string.string_state_receive));
        orderBean.setGoodsCount(resultGoodsCnt);
        orderBean.setsProvinceCityArea(resultFromPCA);
        orderBean.setrProvinceCityArea(resultToPCA);
        orderBean.setOrderCode(orderCode);
        orderBean.setActualMoney(actualMoney);
        orderBean.setCalculateType(resultUserType);

//        startGpsX = StringUtils.isEmpty(startGpsX) ? "0" : startGpsX;
//        startGpsY = StringUtils.isEmpty(startGpsY) ? "0" : startGpsY;
//        endGpsX = StringUtils.isEmpty(endGpsX) ? "0" : endGpsX;
//        endGpsY = StringUtils.isEmpty(endGpsY) ? "0" : endGpsY;
        orderBean.setStartGpsX(startGpsX);
        orderBean.setStartGpsY(startGpsY);
        orderBean.setEndGpsX(endGpsX);
        orderBean.setEndGpsY(endGpsY);
        return orderBean;
    }


    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menuItem1).setVisible(true).setTitle("快速下单");
        menu.findItem(R.id.menuItem2).setVisible(false);
        return Flag.ToPlaceOrder_FromCurrentMission == fromWhichPage ||
                Flag.ToPlaceOrder_FromMissionRecord == fromWhichPage;
//        return placeOrderWhichActivity.equals(Flag.WHICH_ORDER_PLACE);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterMyReceiver(lbm, receiver);
//        try {
//            geoCode.destroy();
//
//        } catch (NullPointerException e) {
//            e.printStackTrace();
//        }

    }
}